<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form :inline="true" :model="formInline" ref="formInline" label-width="80px" size="small" class="form-flex-item">
          <el-row :gutter="20">
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item :label="'검색'|language" prop="keyword">
                <el-input v-model="formInline.keyword" :placeholder="'검색어: 이름, 이메일, 휴대폰 번호'|language" @keyup.enter.native="handleSearch"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">{{'검색'| language}}</el-button>
                <el-button size="small" @click="resetForm('formInline')">{{'초기화'| language}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">기업회원</div>
            </div>
            <div class="main-table-toolbar-option">
              <!-- <el-button type="primary" size="mini" icon="el-icon-plus" style="margin-right:5px" @click="confirmAddUser">{{'추가'| language}}</el-button> -->
              <!-- <el-divider direction="vertical"></el-divider> -->
              <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'다운로드'|language" placement="top">
                  <i @click="downloadFile('/api/enterprise/index', '기업회원')" class="el-icon-download"></i>
                </el-tooltip>
              </el-link>
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'초기화'|language" placement="top">
                  <i @click="getUserList()" class="el-icon-refresh-right"></i>
                </el-tooltip>
              </el-link> -->
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange"
              @sortChange="sortChange">
              <template v-slot:status="slotProps">
                <el-tag v-if="slotProps.callback.row.deleted_at" type="danger" effect="dark" size="small">강제탈퇴</el-tag>
                <el-tag v-else type="success" effect="dark" size="small">사용중</el-tag>
              </template>
              <template v-slot:time="slotProps">
                <span>{{slotProps.callback.row.start_time}} - {{slotProps.callback.row.end_time}}</span>
              </template>
              <template v-slot:image="slotProps">
                <el-image
                  v-if="slotProps.callback.row.has_one_image"
                  style="width: 100px; height: 100px"
                  :src="slotProps.callback.row.has_one_image ? slotProps.callback.row.has_one_image.url : ''"
                  fit="contain"></el-image>
              </template>
              <template v-slot:operation="slotProps">
                <el-button
                  @click="handleShow(slotProps.callback.row.id)"
                  type="text">
                  {{'조회'| language}}
                </el-button>
                <el-button
                  @click="handlePassword(slotProps.callback.row)"
                  type="text">
                  비밀번호
                </el-button>
                <el-button
                  @click="handleEdit(slotProps.callback.row)"
                  v-show="!slotProps.callback.row.deleted_at"
                  type="text">
                  수정
                </el-button>
                <el-divider direction="vertical"></el-divider>
                <el-popconfirm
                  title="정말로 복구 하시겠습니까?"
                  @onConfirm="handleRe(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="slotProps.callback.row.deleted_at"
                    type="text">
                    {{'복구'| language}}
                  </el-button>
                </el-popconfirm>
                <el-popconfirm
                  title="정말 강제 탈퇴 하시겠습니까?"
                  @onConfirm="handleDestroy(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="!slotProps.callback.row.deleted_at"
                    type="text"
                    style="color:#ff4949">
                    {{'강제탈퇴'| language}}
                  </el-button>
                </el-popconfirm>
                <el-popconfirm
                  title="회원 정보를 삭제하시면, 더 이상 조회가 불가합니다."
                  @onConfirm="handleDestroy(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="slotProps.callback.row.deleted_at"
                    type="text"
                    style="padding-left:15px;color:#f56c6c">
                    {{'삭제'| language}}
                  </el-button>
                </el-popconfirm>
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogDetail.title"
      custom-class="dialog-content"
      :visible.sync="dialogDetail.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="900px">
      <div class="dialog-body-content">
        <div class="resume-detail-template">
          <div><label>{{'이메일'|language}}：</label><span>{{dialogDetail.detailData.email}}</span></div>
          <div><label>{{'연락처'|language}}：</label><span>{{dialogDetail.detailData.phone}}</span></div>
          <div><label>{{'이름'|language}}：</label><span>{{dialogDetail.detailData.name}}</span> </div>
          <div><label>{{'성별'|language}}：</label><span>{{dialogDetail.detailData.sex === 1 ? '남자' : '여성'}}</span> </div>
          <div><label>{{'주소'|language}}：</label><span>{{dialogDetail.detailData.city_area}}</span> </div>
          <div><label>{{'상세주소'|language}}：</label><span>{{dialogDetail.detailData.address}}</span> </div>
          <div><label>{{'사업자등록번호'|language}}：</label><span>{{dialogDetail.detailData.business_license}}</span> </div>
          <div><label>{{'기업명'|language}}：</label><span>{{dialogDetail.detailData.company}}</span> </div>
          <div><label>{{'대표자명'|language}}：</label><span>{{dialogDetail.detailData.representative}}</span> </div>
          <div>
            <label>{{'업종'|language}}：</label>
            <el-select v-model="dialogDetail.detailData.company_type" size="small" disabled>
              <el-option
                v-for="item in listTypeInfo.enterprise_form"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <label>{{'기업형태'|language}}：</label>
            <span>{{(dialogDetail.detailData.enterprise1 ? dialogDetail.detailData.enterprise1.name : '' ) + (dialogDetail.detailData.enterprise2 ? ' / ' + dialogDetail.detailData.enterprise2.name : '' )}}</span>
          </div>
          <div>
            <label>{{'가입경로'|language}}：</label>
            <span>{{dialogDetail.detailData.registration_path_name}}</span>
          </div>
          <div>
            <label>{{'개인정보유효기간'|language}}：</label>
            <el-select v-model="dialogDetail.detailData.expire_years_personal" size="small" disabled>
              <el-option
                v-for="item in listTypeInfo.expire_years_personal"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :title="dialogPassword.title"
      custom-class="dialog-content"
      :visible.sync="dialogPassword.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="550px">
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          @handleEventChange="handleEventChange">
        </form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogPassword.dialogVisible = false">{{'취소'| language}}</el-button>
        <el-button size="small" type="primary" @click="handleSubmitPassword">{{'확인'| language}}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="dialogUserInfo.title"
      custom-class="dialog-content"
      :visible.sync="dialogUserInfo.dialogVisible"
      :destroy-on-close="false"
      top="5%"
      width="550px">
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formUserInfo.ref"
          :data="formUserInfo.data"
          :field-list="formUserInfo.fieldList"
          :rules="formUserInfo.rules"
          :label-width="formUserInfo.labelWidth"
          :list-type-info="listTypeInfo">
          <template v-slot:form-item-enterprise_form >
            <el-select v-model="formUserInfo.data.enterprise_form1" @change="changeEnterpriseForm" style="width:160px" size="small">
              <el-option
                v-for="item in listTypeInfo.enterprise_form1"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="formUserInfo.data.enterprise_form2" v-if="formUserInfo.data.enterprise_form1 === 1" style="margin-left:20px;width:180px" size="small">
              <el-option
                v-for="item in listTypeInfo.enterprise_form2"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogUserInfo.dialogVisible = false">{{'취소'| language}}</el-button>
        <el-button size="small" type="primary" @click="handleSubmitUserInfo">{{'확인'| language}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import myTable from '_c/Table'
import { deepClone, mergeObjOfValue, changeOption } from '@/utils'
import FormPage from '_c/FormPage'
import * as userApi from '@/api/user/index'
import { publicEvents } from '@/mixins'
import { getIndustry, getDictData } from '@/api/app'
import { getShapeList } from '@/api/setting/shape'
const formInfoData = {
  user_id: '',
  password: '',
  password_confirmation: ''
}
const formUserInfoData = {
  user_id: '',
  email: '',
  phone: '',
  name: '',
  sex: '',
  city_area: '',
  address: '',
  registration_path: '',
  expire_years_personal: '',
  expire_privacy_created: '',
  business_license: '',
  // birthday: '',
  company: '',
  representative: '',
  company_type: '',
  enterprise_form1: '',
  enterprise_form2: '',
  enterprise_form3: '',
  enterprise_form: []
}
export default {
  name: 'company-user',
  data () {
    return {
      formInline: {
        keyword: ''
      },
      columns: [{
        label: '상태',
        prop: '',
        width: 110,
        slot: 'status',
        sortable: true
      }, {
        label: '이름',
        prop: 'name',
        sortable: true
      }, {
        label: '기업명',
        prop: 'company',
        sortable: true
      }, {
        label: '성별',
        prop: 'sex',
        sortable: true
      }, {
        label: '휴대폰 번호',
        prop: 'phone',
        sortable: true
      }, {
        label: '이메일',
        prop: 'email',
        width: 160,
        sortable: true
      }, {
        label: '가입일자',
        prop: 'created_at',
        width: 180,
        sortable: true
      }, {
        label: '관리',
        prop: '',
        width: 260,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogDetail: {
        dialogVisible: false,
        title: '회원정보',
        detailData: {}
      },
      dialogPassword: {
        dialogVisible: false,
        title: '비밀번호 수정'
      },
      dialogUserInfo: {
        dialogVisible: false,
        title: '정보관리'
      },
      listTypeInfo: {
        sign_form: [],
        sex: [
          {
            label: '남자',
            value: 1
          }, {
            label: '여성',
            value: 2
          }
        ],
        company_type: [],
        enterprise_form: [],
        expire_years_personal: [
          {
            label: '1년',
            value: 1
          }, {
            label: '5년',
            value: 5
          }, {
            label: '10년',
            value: 30
          }, {
            label: '탈퇴시',
            value: 0
          }
        ],
        enterprise_form1: [],
        enterprise_form2: []
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '비밀번호', value: 'password', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '비밀번호 확인', value: 'password_confirmation', width: '260', type: 'input', className: 'el-form-block', required: true, event: 'changePasswordConfirmation' }
        ],
        rules: {},
        labelWidth: '150px'
      },
      formUserInfo: {
        ref: null,
        data: formUserInfoData,
        fieldList: [
          { label: '이메일', value: 'email', type: 'input', className: 'el-form-block', required: true },
          { label: '연락처', value: 'phone', type: 'input', className: 'el-form-block', required: true },
          { label: '이름', value: 'name', type: 'input', className: 'el-form-block', required: true },
          { label: '성별', value: 'sex', type: 'radio', className: 'el-form-block', required: true, list: 'sex' },
          { label: '주소', value: 'city_area', type: 'input', className: 'el-form-block', required: true },
          { label: '상세주소', value: 'address', type: 'input', className: 'el-form-block', required: true },
          // { label: '생년월일', value: 'birthday', type: 'date', className: 'el-form-block', required: true },
          // { label: '등록시간', value: 'expire_privacy_created', type: 'date', dateType: 'date', className: 'el-form-block', required: true },
          // { label: '주소', value: 'area', slot: true, className: 'el-form-block', required: true },
          { label: '사업자등록번호', value: 'business_license', type: 'input', className: 'el-form-block', required: true },
          { label: '기업명', value: 'company', type: 'input', className: 'el-form-block', required: true },
          { label: '대표자명', value: 'representative', type: 'input', className: 'el-form-block', required: true },
          { label: '업종', value: 'company_type', type: 'select', className: 'el-form-block', required: true, list: 'enterprise_form' },
          // { label: '업종', value: 'enterprise_form', type: 'cascader', clearable: true, filterable: true, className: 'el-form-block', required: true, list: 'enterprise_form' },
          { label: '기업형태', value: 'enterprise_form', slot: true, className: 'el-form-block', required: true },
          { label: '가입경로', value: 'registration_path', type: 'select', className: 'el-form-block', required: true, list: 'sign_form' },
          { label: '개인정보유효기간', value: 'expire_years_personal', type: 'select', className: 'el-form-block', required: true, list: 'expire_years_personal' }
        ],
        rules: {},
        labelWidth: '130px'
      },
      sortParams: {}
    }
  },
  components: {
    myTable,
    FormPage
  },
  mixins: [publicEvents],
  mounted () {
    this.getSignForm('sign_form')
    this.formInfo.data = deepClone(formInfoData)
    this.getShapeList()
    this.getIndustry()
    this.getUserList()
  },
  methods: {
    getUserList () {
      const data = {
        ...this.formInline,
        ...this.sortParams,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      userApi.getEnterpriseList(data).then(res => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      }).catch(() => {
        this.loading = false
      })
    },
    getSignForm (key) {
      getDictData(key).then(res => {
        const arr = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.id)
          }
        })
        this.listTypeInfo[key] = arr
      })
    },
    getShapeList () {
      getShapeList().then(res => {
        this.listTypeInfo.enterprise_form1 = res.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        const findCur = res.filter(item => item.id === 1)
        if (findCur.length) {
          this.listTypeInfo.enterprise_form2 = findCur[0].children.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
        }
      })
    },
    changeEnterpriseForm (val) {
      if (val !== 1) {
        this.formUserInfo.data.enterprise_form2 = null
      }
    },
    getIndustry () {
      getIndustry().then(res => {
        res.forEach(element => {
          if (element.children) {
            delete element.children
          }
        })
        this.listTypeInfo.enterprise_form = changeOption(res, { value: 'id', label: 'name' })
      })
    },
    // handleDeleteUser (id) {
    //   userApi.deleteUser({ id }).then(res => {
    //     this.getUserList()
    //   })
    // },
    sortChange (val) {
      this.pagination.currentPage = 1
      if (val.order === 'ascending') {
        this.sortParams = {
          sort: 'asc',
          order_by: val.prop
        }
      } else if (val.order === 'descending') {
        this.sortParams = {
          sort: 'desc',
          order_by: val.prop
        }
      } else {
        this.sortParams = {}
      }
      this.getUserList()
    },
    handleShow (id) {
      this.dialogDetail.dialogVisible = true
      userApi.showEnterprise({ id }).then(res => {
        this.dialogDetail.detailData = res
        this.dialogDetail.detailData.company_type = parseInt(res.company_type)
      })
    },
    handleDestroy (id) {
      userApi.destroyEnterprise({ id }).then(res => {
        this.getUserList()
      })
    },
    handlePassword (rowData) {
      this.formInfo.data.user_id = rowData.id
      this.dialogPassword.dialogVisible = true
    },
    handleEdit (rowData) {
      this.formUserInfo.data.id = rowData.id
      userApi.showEnterprise({ id: rowData.id }).then(res => {
        mergeObjOfValue(this.formUserInfo.data, res)
        this.formUserInfo.data.enterprise_form = []
        if (res.enterprise_form1) {
          this.formUserInfo.data.enterprise_form1 = parseInt(res.enterprise_form1)
        }
        if (res.enterprise_form2) {
          this.formUserInfo.data.enterprise_form2 = parseInt(res.enterprise_form2)
        }
        if (res.enterprise_form3) {
          this.formUserInfo.data.enterprise_form3 = parseInt(res.enterprise_form3)
        }
        this.formUserInfo.data.company_type = parseInt(res.company_type)
        this.dialogUserInfo.dialogVisible = true
      })
    },
    handleSubmitPassword () {
      if (this.formInfo.data.password === this.formInfo.data.password_confirmation) {
        userApi.restMemberPassword(this.formInfo.data).then(res => {
          this.dialogPassword.dialogVisible = false
          this.formInfo.data.password = ''
          this.formInfo.data.password_confirmation = ''
          this.$message({
            type: 'success',
            message: '성공하였습니다'
          })
        })
      }
    },
    handleSubmitUserInfo () {
      const data = {
        ...this.formUserInfo.data
      }
      if (data.enterprise_form1 !== 1) {
        data.enterprise_form2 = null
      }
      // data.enterprise_form1 = data.enterprise_form[0] || null
      // data.enterprise_form2 = data.enterprise_form[1] || null
      // data.enterprise_form3 = data.enterprise_form[2] || null
      console.log(data)
      userApi.updateEnterprise(data).then(res => {
        this.dialogUserInfo.dialogVisible = false
        this.getUserList()
      })
    },
    handleRe (id) {
      userApi.reEnterprise({ id }).then(res => {
        this.getUserList()
      })
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getUserList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getUserList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    handleEventChange (event, data) {
      switch (event) {
        case 'changePasswordConfirmation': {
          if (this.formInfo.data.password === '') {
            this.$message({
              message: '새로운 비밀번호를 입력해주세요.',
              type: 'warning'
            })
            this.formInfo.data.password_confirmation = ''
          } else if (this.formInfo.data.password !== this.formInfo.data.password_confirmation) {
            this.$message({
              message: '비밀번호와 비밀번호 확인이 다릅니다.',
              type: 'error'
            })
            this.formInfo.data.password_confirmation = ''
          }
          break
        }
      }
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getUserList()
    }
  }
}
</script>
